import { createContext, useContext, useState, useCallback, useMemo } from 'react';
import type { ReactNode } from 'react';
import type { CheckItemTemplate, TemplateTable, CreateTemplateParams } from '@/types/template';
import { templateApi } from '@/api/template';

interface TemplateState {
  currentTemplate: TemplateTable | null;
  /** 已上传模板列表 */
  templates: TemplateTable[];
}

const initialState: TemplateState = {
  currentTemplate: null,
  templates: [],
};

interface TemplateContextType {
  state: TemplateState;
  /* 导入流程相关 */
  resetTemplate: () => void;
  createNewTemplate: (params: CreateTemplateParams) => Promise<TemplateTable>;
  updateTemplateItems: (items: CheckItemTemplate[]) => Promise<void>;
  addItems: (items: CheckItemTemplate[]) => void;
  updateItem: (id: string, updates: Partial<CheckItemTemplate>) => void;
  removeItem: (id: string) => void;
  setCurrentTemplate: (template: TemplateTable) => void;
  setDefaultMaturityLevel: (level: number) => void;
  /* 模板列表相关 */
  fetchTemplates: () => Promise<void>;
  deleteTemplate: (id: string) => Promise<void>;
}

const TemplateContext = createContext<TemplateContextType | null>(null);

export function TemplateProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<TemplateState>(initialState);

  const setCurrentTemplate = useCallback((template: TemplateTable) => {
    setState(prev => ({
      ...prev,
      currentTemplate: template
    }));
  }, []);

  const setDefaultMaturityLevel = useCallback((level: number) => {
    setState(prev => {
      if (!prev.currentTemplate) return prev;
      
      return {
        ...prev,
        currentTemplate: {
          ...prev.currentTemplate,
          default_maturity_level: level
        }
      };
    });
  }, []);

  const addItems = useCallback((items: CheckItemTemplate[]) => {
    setState(prev => {
      if (!prev.currentTemplate) return prev;
      
      return {
        ...prev,
        currentTemplate: {
          ...prev.currentTemplate,
          items: [...(prev.currentTemplate.items || []), ...items]
        }
      };
    });
  }, []);

  const updateItem = useCallback((id: string, updates: Partial<CheckItemTemplate>) => {
    setState(prev => {
      if (!prev.currentTemplate) return prev;
      
      return {
        ...prev,
        currentTemplate: {
          ...prev.currentTemplate,
          items: (prev.currentTemplate.items || []).map(item => 
            item.id === id ? { ...item, ...updates } : item
          )
        }
      };
    });
  }, []);

  const removeItem = useCallback((id: string) => {
    setState(prev => {
      if (!prev.currentTemplate) return prev;
      
      return {
        ...prev,
        currentTemplate: {
          ...prev.currentTemplate,
          items: (prev.currentTemplate.items || []).filter(item => item.id !== id)
        }
      };
    });
  }, []);

  const resetTemplate = useCallback(() => {
    setState(initialState);
  }, []);

  const updateImportProgress = useCallback((_progress: number) => {
    // No-op since we're removing import functionality
  }, []);

  const createNewTemplate = useCallback(async (params: CreateTemplateParams) => {
    const { name, description, assessmentType, items, defaultMaturityLevel } = params;
    
    const newTemplate = await templateApi.createTemplate(
      name,
      description,
      assessmentType,
      items,
      defaultMaturityLevel
    );
    
    setState(prev => ({
      ...prev,
      currentTemplate: newTemplate
    }));
    
    return newTemplate;
  }, []);

  const updateTemplateItems = useCallback(async (items: CheckItemTemplate[]) => {
    if (!state.currentTemplate) return;
    
    setState(prev => ({
      ...prev,
      currentTemplate: {
        ...prev.currentTemplate!,
        items: [...(prev.currentTemplate?.items || []), ...items]
      }
    }));
  }, [state.currentTemplate]);

  /** 获取模板列表 */
  const fetchTemplates = useCallback(async () => {
    const { items } = await templateApi.getTemplates();
    setState(prev => ({ ...prev, templates: items }));
  }, []);

  /** 删除模板 */
  const deleteTemplate = useCallback(async (id: string) => {
    await templateApi.deleteTemplate(id);
    setState(prev => ({
      ...prev,
      templates: prev.templates.filter(t => t.id !== id),
      currentTemplate: prev.currentTemplate?.id === id ? null : prev.currentTemplate,
    }));
  }, []);

  const value = useMemo(() => ({
    /* state */
    state,
    /* 导入流程 */
    resetTemplate,
    createNewTemplate,
    updateTemplateItems,
    addItems,
    updateItem,
    removeItem,
    setCurrentTemplate,
    setDefaultMaturityLevel,
    updateImportProgress,
    /* 模板列表 */
    fetchTemplates,
    deleteTemplate,
  }), [
    state,
    resetTemplate,
    createNewTemplate,
    updateTemplateItems,
    addItems,
    updateItem,
    removeItem,
    setCurrentTemplate,
    setDefaultMaturityLevel,
    updateImportProgress,
    fetchTemplates,
    deleteTemplate,
  ]);

  return (
    <TemplateContext.Provider value={value}>
      {children}
    </TemplateContext.Provider>
  );
}

export function useTemplate() {
  const context = useContext(TemplateContext);
  if (!context) {
    throw new Error('useTemplate must be used within a TemplateProvider');
  }
  return context;
}
